<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>键盘事件</title>
    <style>
        p {
            white-space: pre;
            line-height: 1.5;
            color: gray;
        }
        
        .box {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            top: 100px;
            left: 400px;
        }
        
        .green {
            background-color: green;
        }
        
        .yellow {
            background-color: yellow;
        }
        
        .blue {
            background-color: blue;
        }
        
        .bigger {
            transform: scale(1.5);
        }
        
        .smaller {
            transform: scale(0.7);
        }
    </style>
</head>

<body>
    <p>
        提示： 红色方块为键盘操作区域，您可以进行如下操作： 上：↑ 下：↓ 左：← 右：→ Ctrl + 1 : 背景变为绿色 Ctrl + 2 : 背景变为黄色 Ctrl + 3 : 背景变为蓝色 Ctrl + ↑ : 放大 Ctrl + ↓ : 缩小
    </p>
    <div class="box"></div>
    <div class="b1"></div>
    <script>
        let box = document.querySelector('.box')
        let _left = parseFloat(getComputedStyle(box).left)
        let _top = parseFloat(getComputedStyle(box).top)
        let rawBoxClass = box.className
            // window.onkeydown = function (e) {
            //     console.log(e)
            //     if(e.keyCode == 38){
            //         console.log('keyup')
            //         box.style.top = `${--y}px`
            //     }
            //     if(e.keyCode == 49 && e.ctrlKey){
            //         box.classList.add('green')
            //     }

        // }
        let speed = 10
        window.onkeydown = function(e) {
            console.log(e)
            if (e.keyCode == 38) {
                _top -= speed
                box.style.top = _top + "px"
            }
            if (e.keyCode == 40) {
                _top += speed
                box.style.top = _top + "px"
            }
            if (e.keyCode == 37) {
                _left -= speed
                box.style.left = _left + "px"
            }
            if (e.keyCode == 39) {
                _left += speed
                box.style.left = _left + "px"
            }
            if (e.keyCode == 49 && e.ctrlKey) {
                box.className = rawBoxClass + " " + "green"
            }
            if (e.keyCode == 50 && e.ctrlKey) {
                box.className = rawBoxClass + " " + "yellow"
            }
            if (e.keyCode == 38 && e.ctrlKey) {
                box.classList.remove('smaller')
                box.classList.add('bigger')
            }
            if (e.keyCode == 40 && e.ctrlKey) {
                box.classList.remove('bigger')
                box.classList.add('smaller')
            }
        }
    </script>
</body>

</html>